package com.liwalo.dao;

// Generated 24-ago-2013 14:46:30 by Hibernate Tools 3.6.0

import static org.hibernate.criterion.Example.create;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.naming.InitialContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.liwalo.entities.MediosContacto;
import com.liwalo.entities.Pedido;
import com.liwalo.entities.TiendaProducto;
import com.liwalo.entities.Usuario;
import com.liwalo.utils.HibernateUtil;

/**
 * Home object for domain model class Pedido.
 * @see com.liwalo.dao.Pedido
 * @author Hibernate Tools
 */
public class PedidoDAO {

	private static final Log log = LogFactory.getLog(PedidoDAO.class);

	private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	protected SessionFactory getSessionFactory() {
		try {
			return (SessionFactory) new InitialContext()
					.lookup("SessionFactory");
		} catch (Exception e) {
			log.error("Could not locate SessionFactory in JNDI", e);
			throw new IllegalStateException(
					"Could not locate SessionFactory in JNDI");
		}
	}

	public void persist(Pedido transientInstance) {
		log.debug("persisting Pedido instance");
		Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
		try {
			
			 session.save(transientInstance);
	         tx.commit();
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	public void attachDirty(Pedido instance) {
		log.debug("attaching dirty Pedido instance");
		Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
		try {
			session.saveOrUpdate(instance);
			 tx.commit();
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Pedido instance) {
		log.debug("attaching clean Pedido instance");
		try {
			sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void delete(Pedido persistentInstance) {
		log.debug("deleting Pedido instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Pedido merge(Pedido detachedInstance) {
		log.debug("merging Pedido instance");
		try {
			Pedido result = (Pedido) sessionFactory.getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public Pedido findById(int id) {
		log.debug("getting Pedido instance with id: " + id);
		try {
			Pedido instance = (Pedido) sessionFactory.getCurrentSession().get(
					"com.liwalo.dao.Pedido", id);
			if (instance == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
			}
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<Pedido> findByExample(Pedido instance) {
		log.debug("finding Pedido instance by example");
		try {
			List<Pedido> results = (List<Pedido>) sessionFactory
					.getCurrentSession()
					.createCriteria("com.liwalo.dao.Pedido")
					.add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	
	public Long formIdPedido() {
        String idPedido = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Pedido.class,"peidido")
        .add(Restrictions.between("numeroPedido", Long.valueOf(idPedido + "00000"), Long.valueOf(idPedido + "99999")))
        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        criteria.setProjection(Projections.max("numeroPedido"));
        
       

        if(criteria.list().isEmpty() || criteria.uniqueResult()==null){
            idPedido += "00001";
        }else{
            idPedido = ((Long) criteria.list().get(0) + 1) + "";
        }

        return Long.valueOf(idPedido);
	}
	
	public Pedido findbyNumeroPedido(Pedido pedido) {
		log.debug("getting Pedido instance with id: " + pedido);
		List<Pedido> result = null;
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		try{
            
           

            Criteria criteria = session.createCriteria(Pedido.class , "pedido")
					.add(Restrictions.eq("pedido.numeroPedido", pedido.getNumeroPedido()))
					;
            result = criteria.list();
            


            if(result != null && result.size()>0){
            	Pedido pedidovo=(Pedido)result.get(0);
            	
                return pedidovo;
            }



		} catch (RuntimeException re) {
			throw re;
		}


            return null;
	}
}
